package controller;

import com.alibaba.fastjson.JSON;
import dao.RepairDao;
import entity.Baoxiu;
import service.RepairService;
import service.impl.RepairServiceImpl;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/repairController")
public class RepairController extends HttpServlet {
    private RepairService dormitoryService = new RepairServiceImpl();
    private Object ExcelUtil;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String op = request.getParameter("op");
        RepairService d= new RepairServiceImpl();
        HttpSession session = request.getSession(true);

        if ("query".equals(op)) {
            String orderId = request.getParameter("orderId");
            String roomNumber = request.getParameter("roomNumber");
            int page = request.getParameter("page") == null ? 0 : Integer.parseInt(request.getParameter("page"));
            int pageSize = 2;

            try {
                int totalCount = dormitoryService.getTotalCount(
                        orderId != null && !orderId.isEmpty() ? Integer.parseInt(orderId) : null,
                        roomNumber
                );
                int totalPages = (int) Math.ceil((double)totalCount / pageSize);

                List<Baoxiu> list = dormitoryService.chaxun(
                        orderId != null && !orderId.isEmpty() ? Integer.parseInt(orderId) : null,
                        roomNumber,
                        page,
                        pageSize
                );

                Map<String, Object> result = new HashMap<>();
                result.put("list", list);
                result.put("total", totalCount);
                result.put("page", page);
                result.put("pageSize", pageSize);
                result.put("totalPages", totalPages);

                out.write(JSON.toJSONString(result));
            } catch (Exception e) {
                e.printStackTrace();
                out.write("{\"error\":\"查询失败\"}");
            }
        } else if ("add".equals(op)) {
            try {
                Baoxiu baoxiu = new Baoxiu();
                baoxiu.setRoomNumber(request.getParameter("roomNumber"));
                baoxiu.setName(request.getParameter("name"));
                baoxiu.setDescription(request.getParameter("description"));
                baoxiu.setStatus("待处理");
                baoxiu.setCreatedAt(new Date().toString());
                int result = 0;
                if(dormitoryService.tjpd(baoxiu)==null || dormitoryService.tjpd(baoxiu)==0){
                    out.write("宿舍号和报修人不匹配");
                }else {
                    baoxiu.setStudentId(dormitoryService.tjpd(baoxiu));
                    result= dormitoryService.tianjia(baoxiu);
                    if (result > 0) {
                        out.write("报修添加成功");
                    } else {
                        out.write("添加失败");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();

            }
        } else if("complete".equals(op)){
            int orderId = Integer.parseInt(request.getParameter("orderId"));
            // 获取当前日期时间
            Date now = new Date();

            // 定义格式
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            // 格式化输出
            String formattedDateTime = formatter.format(now);
            try {
                int result = dormitoryService.updateStatus(orderId, "已完成", null, formattedDateTime);
                out.write("{\"success\":" + (result > 0) + "}");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if("withdraw".equals(op)){
            int orderId = Integer.parseInt(request.getParameter("orderId"));


            try {
                int result = dormitoryService.updateStatus(orderId,"已撤回",null,null);
                out.write("{\"success\":" + (result > 0) + "}");
            } catch (Exception e) {
                e.printStackTrace();
                out.write("{\"success\":false,\"message\":\"撤回失败\"}");
            }
        }
        else if("process".equals(op)){
            int orderId = Integer.parseInt(request.getParameter("orderId"));


            // 获取当前日期时间
            Date now = new Date();

            // 定义格式
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            // 格式化输出
            String formattedDateTime = formatter.format(now);

            try {
                int result = dormitoryService.updateStatus(orderId,"处理中",formattedDateTime,null);
                out.write("{\"success\":" + (result > 0) + "}");
            } catch (Exception e) {
                e.printStackTrace();
                out.write("{\"success\":false,\"message\":\"处理失败\"}");
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

}